<?php

namespace app\controllers;

use Yii;
use app\models\AccProject;
use app\models\Project;
use app\models\User;
use app\models\AccProjectSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\helpers\ArrayHelper;

/**
 * AccProjectController implements the CRUD actions for AccProject model.
 */
class AccProjectController extends Controller
{
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }

    /**
     * Lists all AccProject models.
     * @return mixed
     */
    public function actionIndex($acc_id=null)
    {
        $searchModel = new AccProjectSearch();
        $queryParams = array_merge(array(),Yii::$app->request->getQueryParams());
		
		if($acc_id!=null)
		{
			$queryParams['AccProjectSearch']['acc_id'] = $acc_id;
		}
        $dataProvider = $searchModel->search($queryParams);

        return $this->render($acc_id==null?'index':'index_user', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single AccProject model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new AccProject model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new AccProject();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {			
			//gửi mail cho admin
			Yii::$app->mail->compose()
				 ->setFrom('hotro@thongtinmientay.vn')
				 ->setTo(UserController::GetAdminEmail())
				 ->setSubject('[CAPTCHA TTMT] Thông báo')
				 ->setHtmlBody('<b>Chào quản trị viên,</b><br/>
				 Có 1 thành viên đăng ký dự án mới.<br/>
				 Vui lòng kiểm tra và cấp tài khoản làm việc cho thành viên <a href='.
				 Yii::$app->UrlManager->createAbsoluteUrl('/').'>tại đây.</a><br/>
				 Trân trọng!')
				 ->send();
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
                'arrayProject' => ProjectController::getProject(),
            ]);
        }
    }

    /**
     * Updates an existing AccProject model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                'model' => $model,
                'arrayProject' => ProjectController::getProject(),
            ]);
        }
    }

    /**
     * Deletes an existing AccProject model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();
		//là người quản trị thì trở về trang index
		if(Yii::$app->user->identity->acc_type==0)
		{
			return $this->redirect(['index']);
		}		
		//là người dùng thường thì trở về trang người dùng
		else
		{
			return $this->redirect(['index', 'acc_id' => Yii::$app->user->identity->acc_id]);
		}
    }

    /**
     * Finds the AccProject model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return AccProject the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = AccProject::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
	
	//lấy danh sách người dùng đăng ký tài khoản
	public static function getAccProject()
    {
		$model = new AccProject();
		$arrayAccProject = ArrayHelper::map($model->findBySql(
					"SELECT  `acc_project`.id, concat(`username`, ' (', `name`, ')') as a_p
					FROM `acc_project` 
					JOIN `user`
					ON `user`.acc_id = `acc_project`.acc_id
                    JOIN `project`
                    ON `project`.id = `acc_project`.project_id
					ORDER BY username")
					->asArray()->all(), 'id', 'a_p');
		return $arrayAccProject;
    }
}
